<template>
  <el-select
    v-model="value"
    :placeholder="props.placeholder"
    clearable
    filterable
    @change="change"
  >
    <el-option
      v-for="item in channelOptions"
      :key="item.channel_id"
      :label="item.channel_name"
      :value="item.channel_id"
    />
  </el-select>
</template>
<script setup>
import useCommonStore from "@/store/modules/common";
const commonStore = useCommonStore();

const rawChannelOptions = computed(() => commonStore.channelOptions);
const filteredChannelOptions = ref();

const props = defineProps({
  modelValue: [String, Number, Array],
  placeholder: {
    type: String,
    default: "请选择",
  },
  type: {
    type: String,
    default: "",
  },
  transportType: {
    type: [String, Number],
    default: "",
  },
});

const { type, transportType } = toRefs(props);

watchEffect(() => {
  if (rawChannelOptions.value && type.value) {
    let options = rawChannelOptions.value;

    if (type.value === "head") {
      options = options.filter((i) => i.delivery_mode === 2);
    } else if (type.value === "tail") {
      options = options.filter((i) => [1, 3].includes(i.delivery_mode));
    }

    if (transportType.value) {
      options = options.filter((i) => i.transport_type === transportType.value);
    }

    // 只有在过滤结果改变时更新，避免不必要的视图更新
    if (filteredChannelOptions.value !== options) {
      filteredChannelOptions.value = options;
    }
  } else {
    // 当type未定义或channelOptions为空时，不设置任何值，避免不必要的计算
    filteredChannelOptions.value = undefined;
  }
});

const channelOptions = computed(() => {
  // 直接返回过滤后的结果或原始数据
  return filteredChannelOptions.value || rawChannelOptions.value;
});

const value = computed(() => {
  return props.modelValue;
});

const emit = defineEmits(["update:modelValue", "change", "changeItem"]);

const change = (val) => {
  const item = channelOptions.value.find((i) => i.channel_id == val);
  emit("update:modelValue", val);
  emit("change", item?.channel_name);
  if (item) {
    emit("changeItem", item);
  }
};
</script>
